<template>
    <div class="task-list-page">
        <div class="operation-bar">
            <div>
                <el-button type="primary" size="small" @click="showAddDialog = true">发布任务</el-button>
                <el-select v-model="sortBy" placeholder="排序方式" size="small" style="width: 120px; margin-left: 20px;"
                    @change="handleSearch">
                    <el-option label="默认" value="" />
                    <el-option label="优先级升序" value="priority_asc" />
                    <el-option label="优先级降序" value="priority_desc" />
                </el-select>

            </div>
            <div class="filter-container">
                <el-input v-model="searchKeyword" placeholder="请输入关键词搜索" size="small" clearable @clear="handleSearch"
                    @keyup.enter.native="handleSearch" style="width: 200px;" />
                <el-button type="primary" size="small" @click="handleSearch">查询</el-button>
            </div>
        </div>

        <div class="table-wrapper">
            <el-table :data="tableData" stripe :row-key="row => row.id" class="table-content">
                <el-table-column prop="id" label="任务ID" header-align="center" align="center" width="70" />
                <el-table-column prop="parent_id" label="父任务ID" header-align="center" align="center" width="90" />
                <el-table-column prop="username" label="任务发布者" header-align="center" align="center" width="100" />
                <el-table-column prop="title" label="任务标题" header-align="center" align="center" />
                <el-table-column prop="status" label="任务状态" header-align="center" align="center" width="90">
                    <template #default="{ row }">
                        <span :class="statusClass(row.status)">{{ formatStatus(row, null, row.status) }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="priority" label="优先级" header-align="center" align="center" width="90">
                    <template #default="{ row }">
                        <span :class="priorityClass(row.priority)">{{ formatPriority(row, null, row.priority) }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="操作" fixed="right" header-align="left" align="left" width="300">
                    <template #default="{ row }">
                        <el-button type="info" size="small" :disabled="row.is_deleted === 1"
                            @click="handleView(row)">详情</el-button>
                        <el-button type="success" size="small" :disabled="row.is_deleted === 1"
                            @click="handleAddSubTask(row)">添加子任务</el-button>
                        <el-button type="primary" size="small" :disabled="row.is_deleted === 1"
                            @click="handleEdit(row)">修改</el-button>
                        <el-button type="danger" size="small" :disabled="row.is_deleted === 1"
                            @click="handleDelete(row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <div class="pagination-container">
            <el-pagination background layout="sizes, prev, pager, next, jumper, ->, total" :page-sizes="[5, 10, 20, 50]"
                :page-size="pageSize" :current-page="currentPage" :total="total" @current-change="handlePageChange"
                @size-change="handleSizeChange" />
        </div>

        <!-- 发布任务弹窗 -->
        <el-dialog title="发布任务" v-model="showAddDialog" width="400px" :before-close="handleAddDialogClose">
            <el-form :model="addForm" ref="addFormRef" label-width="80px" :rules="rules">
                <el-form-item label="标题" prop="title">
                    <el-input v-model="addForm.title" autocomplete="off" />
                </el-form-item>
                <el-form-item label="描述" prop="description">
                    <el-input v-model="addForm.description" type="textarea" rows="3" />
                </el-form-item>
                <el-form-item label="优先级" prop="priority">
                    <el-select v-model="addForm.priority" placeholder="请选择优先级">
                        <el-option label="高" value="high" />
                        <el-option label="中" value="medium" />
                        <el-option label="低" value="low" />
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="handleAddCancel">取消</el-button>
                <el-button type="primary" @click="submitAddForm">确定</el-button>
            </template>
        </el-dialog>

        <el-dialog title="添加子任务" v-model="showSubTaskDialog" width="400px" :before-close="handleSubTaskDialogClose">
            <el-form :model="subTaskForm" ref="subTaskFormRef" label-width="80px" :rules="rules">
                <el-form-item label="标题" prop="title">
                    <el-input v-model="subTaskForm.title" autocomplete="off" />
                </el-form-item>
                <el-form-item label="描述" prop="description">
                    <el-input v-model="subTaskForm.description" type="textarea" rows="3" />
                </el-form-item>
                <el-form-item label="优先级" prop="priority">
                    <el-select v-model="subTaskForm.priority" placeholder="请选择优先级">
                        <el-option label="高" value="high" />
                        <el-option label="中" value="medium" />
                        <el-option label="低" value="low" />
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="handleSubTaskCancel">取消</el-button>
                <el-button type="primary" @click="submitSubTaskForm">确定</el-button>
            </template>
        </el-dialog>

        <!-- 修改任务弹窗 -->
        <el-dialog title="修改任务" v-model="showEditDialog" width="400px" :before-close="handleEditDialogClose">
            <el-form :model="editForm" ref="editFormRef" label-width="80px" :rules="rules">
                <el-form-item label="标题" prop="title">
                    <el-input v-model="editForm.title" autocomplete="off" />
                </el-form-item>
                <el-form-item label="描述" prop="description">
                    <el-input v-model="editForm.description" type="textarea" rows="3" />
                </el-form-item>
                <el-form-item label="优先级" prop="priority">
                    <el-select v-model="editForm.priority" placeholder="请选择优先级">
                        <el-option label="高" value="high" />
                        <el-option label="中" value="medium" />
                        <el-option label="低" value="low" />
                    </el-select>
                </el-form-item>
                <el-form-item label="任务状态" prop="status">
                    <el-select v-model="editForm.status" placeholder="请选择任务状态">
                        <el-option label="待办" value="pending" />
                        <el-option label="进行中" value="working" />
                        <el-option label="已完成" value="completed" />
                        <el-option label="已归档" value="archived" />
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="handleEditCancel">取消</el-button>
                <el-button type="primary" @click="submitEditForm">确定</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { addTaskAPI, getTasksAPI, updateTaskAPI, deleteTaskAPI } from '@/api/task'

const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const searchKeyword = ref('')
const total = ref(0)
const tableData = ref([])
const sortBy = ref('')

const showAddDialog = ref(false)
const addFormRef = ref(null)
const addForm = reactive({
    title: '',
    description: '',
    priority: 'medium',
    parent_id: null
})

const showSubTaskDialog = ref(false)
const subTaskFormRef = ref(null)
const subTaskForm = reactive({
    title: '',
    description: '',
    priority: 'medium',
    parent_id: null
})

const showEditDialog = ref(false)
const editFormRef = ref(null)
const editForm = reactive({
    id: null,
    title: '',
    description: '',
    priority: 'medium',
    status: 'pending',
})

const rules = {
    title: [{ required: true, message: '请输入任务标题', trigger: 'blur' }],
    priority: [{ required: true, message: '请选择优先级', trigger: 'change' }],
}

const formatDate = (row, column, cellValue) => {
    if (!cellValue) return ''
    const date = new Date(cellValue)
    const pad = (n) => n.toString().padStart(2, '0')
    const year = date.getFullYear()
    const month = pad(date.getMonth() + 1)
    const day = pad(date.getDate())
    const hours = pad(date.getHours())
    const minutes = pad(date.getMinutes())
    const seconds = pad(date.getSeconds())
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

const formatStatus = (row, column, cellValue) => {
    const map = {
        pending: '待办',
        working: '进行中',
        completed: '已完成',
        archived: '已归档',
    }
    return map[cellValue] || cellValue
}

const formatPriority = (row, column, cellValue) => {
    const map = {
        high: '高',
        medium: '中',
        low: '低',
    }
    return map[cellValue] || cellValue
}
// 状态样式
const statusClass = (status) => {
    switch (status) {
        case 'pending': return 'status-pending'
        case 'working': return 'status-working'
        case 'completed': return 'status-completed'
        case 'archived': return 'status-archived'
        default: return ''
    }
}
// 优先级样式
const priorityClass = (priority) => {
    switch (priority) {
        case 'high': return 'priority-high'
        case 'medium': return 'priority-medium'
        case 'low': return 'priority-low'
        default: return ''
    }
}

const fetchData = async () => {
    try {
        loading.value = true
        const params = {
            page: currentPage.value,
            page_size: pageSize.value,
            keyword: searchKeyword.value,
            sort_by: sortBy.value,
        }
        const res = await getTasksAPI(params)
        total.value = res.total
        tableData.value = res.tasks
    } catch (error) {
        console.error('获取任务列表失败', error)
    } finally {
        loading.value = false
    }
}

const handlePageChange = (page) => {
    currentPage.value = page
    fetchData()
}

const handleSizeChange = (size) => {
    pageSize.value = size
    currentPage.value = 1
    fetchData()
}

const handleSearch = () => {
    currentPage.value = 1
    fetchData()
}

const handleAddDialogClose = () => {
    resetAddForm()
    showAddDialog.value = false
}

const resetAddForm = () => {
    addForm.title = ''
    addForm.description = ''
    addForm.priority = 'medium'
    addFormRef.value?.clearValidate()
}

const submitAddForm = () => {
    addFormRef.value.validate(async (valid) => {
        if (valid) {
            try {
                await addTaskAPI({
                    title: addForm.title,
                    description: addForm.description,
                    priority: addForm.priority,
                    parent_id: addForm.parentId
                })
                ElMessage.success('发布任务成功')
                showAddDialog.value = false
                fetchData()
                resetAddForm()
            } catch (error) {
                console.error('发布任务失败', error)
            }
        }
    })
}

const handleAddCancel = () => {
    resetAddForm()
    showAddDialog.value = false
}

const handleAddSubTask = (row) => {
    subTaskForm.title = ''
    subTaskForm.description = ''
    subTaskForm.priority = 'medium'
    subTaskForm.parent_id = row.id
    subTaskFormRef.value?.clearValidate()
    showSubTaskDialog.value = true
}

const handleSubTaskDialogClose = () => {
    resetSubTaskForm()
    showSubTaskDialog.value = false
}

const handleSubTaskCancel = () => {
    resetSubTaskForm()
    showSubTaskDialog.value = false
}

const resetSubTaskForm = () => {
    subTaskForm.title = ''
    subTaskForm.description = ''
    subTaskForm.priority = 'medium'
    subTaskForm.parent_id = null
    subTaskFormRef.value?.clearValidate()
}

const submitSubTaskForm = () => {
    subTaskFormRef.value.validate(async (valid) => {
        if (valid) {
            try {
                await addTaskAPI({
                    title: subTaskForm.title,
                    description: subTaskForm.description,
                    priority: subTaskForm.priority,
                    parent_id: subTaskForm.parent_id
                })
                ElMessage.success('子任务添加成功')
                showSubTaskDialog.value = false
                fetchData()
                resetSubTaskForm()
            } catch (error) {
                console.error('添加子任务失败', error)
            }
        }
    })
}


const handleEdit = (row) => {
    editForm.id = row.id
    editForm.title = row.title
    editForm.description = row.description
    editForm.priority = row.priority
    editForm.status = row.status
    showEditDialog.value = true
}

const handleEditDialogClose = () => {
    resetEditForm()
    showEditDialog.value = false
}

const resetEditForm = () => {
    editForm.id = null
    editForm.title = ''
    editForm.description = ''
    editForm.priority = 'medium'
    editForm.status = 'pending'
    editFormRef.value?.clearValidate()
}

const submitEditForm = () => {
    editFormRef.value.validate(async (valid) => {
        if (valid) {
            try {
                // 这里需要调用 updateTaskAPI，假设已实现
                await updateTaskAPI(editForm.id, {
                    title: editForm.title,
                    description: editForm.description,
                    priority: editForm.priority,
                    status: editForm.status,
                })
                ElMessage.success('修改任务成功')
                showEditDialog.value = false
                fetchData()
                resetEditForm()
            } catch (error) {
                console.error('修改任务失败', error)
            }
        }
    })
}

const handleEditCancel = () => {
    resetEditForm()
    showEditDialog.value = false
}

const handleDelete = async (row) => {
    try {
        await ElMessageBox.confirm(`确定删除任务 ${row.id} 吗？（软删除）`, '删除确认', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        })
        await deleteTaskAPI(row.id)
        ElMessage.success(`任务 ${row.id} 已删除`)
        fetchData()
    } catch (err) {
        if (err !== 'cancel') {
            console.error('删除失败')
        } else {
            ElMessage.info('已取消删除')
        }
    }
}


import { useRouter } from 'vue-router'
const router = useRouter()
const handleView = (row) => {
    router.push(`/harborSpace/trace/task/${row.id}`)
}



onMounted(async () => {
    await fetchData()
})




</script>

<style scoped>
.task-list-page {
    .task-list-page {
        width: 100%;
        box-sizing: border-box;
    }

    /* 任务状态样式 */
    .status-pending {
        background: #fff7b8;
        /* 更柔和的浅黄 */
        color: #ad8b00;
        /* 保留深黄，易识别 */
        padding: 2px 12px;
        border-radius: 12px;
        font-weight: bold;
        font-size: 13px;
        min-width: 40px;
        display: inline-block;
        text-align: center;
    }

    .status-working {
        background: #bae7ff;
        /* 更柔和的浅蓝 */
        color: #0050b3;
        /* 深蓝突出状态 */
        padding: 2px 12px;
        border-radius: 12px;
        font-weight: bold;
        font-size: 13px;
        min-width: 40px;
        display: inline-block;
        text-align: center;
    }

    .status-completed {
        background: #d9f7be;
        /* 更清新的浅绿 */
        color: #237804;
        /* 稳重的绿色 */
        padding: 2px 12px;
        border-radius: 12px;
        font-weight: bold;
        font-size: 13px;
        min-width: 40px;
        display: inline-block;
        text-align: center;
    }

    .status-archived {
        background: #f0f0f0;
        /* 纯净浅灰 */
        color: #595959;
        /* 中灰 */
        padding: 2px 12px;
        border-radius: 12px;
        font-weight: bold;
        font-size: 13px;
        min-width: 40px;
        display: inline-block;
        text-align: center;
    }

    /* 优先级样式 */
    .priority-high {
        background: #ffa39e;
        /* 亮红色，突出但不刺眼 */
        color: #a8071a;
        /* 深红色 */
        padding: 2px 12px;
        border-radius: 12px;
        font-weight: bold;
        font-size: 13px;
        min-width: 40px;
        display: inline-block;
        text-align: center;
    }

    .priority-medium {
        background: #ffe58f;
        /* 柔和橙黄 */
        color: #ad6800;
        /* 稳重橙色 */
        padding: 2px 12px;
        border-radius: 12px;
        font-weight: bold;
        font-size: 13px;
        min-width: 40px;
        display: inline-block;
        text-align: center;
    }

    .priority-low {
        background: #b7eb8f;
        /* 明亮绿色 */
        color: #237804;
        /* 绿色 */
        padding: 2px 12px;
        border-radius: 12px;
        font-weight: bold;
        font-size: 13px;
        min-width: 40px;
        display: inline-block;
        text-align: center;
    }

    .operation-bar {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 15px;
    }

    .filter-container {
        display: flex;
        gap: 10px;
        align-items: center;
    }

    .filter-container .el-input input {
        height: 28px !important;
        line-height: 28px !important;
        padding: 0 10px !important;
    }

    .pagination-container {
        margin-top: 20px;
        text-align: right;
    }

    .table-wrapper {
        overflow-x: auto;
        scrollbar-width: thin;
        scrollbar-color: #888 #f1f1f1;
    }

    .table-content {
        width: 100%;
        min-width: 900px;
    }

    .table-wrapper::-webkit-scrollbar {
        height: 8px;
    }

    .table-wrapper::-webkit-scrollbar-track {
        background: #f1f1f1;
        border-radius: 4px;
    }

    .table-wrapper::-webkit-scrollbar-thumb {
        background-color: #888;
        border-radius: 4px;
        border: 2px solid #f1f1f1;
    }

    .table-wrapper::-webkit-scrollbar-thumb:hover {
        background-color: #555;
    }

    /* 用户是否删除标签样式 */
    .normal-tag {
        display: inline-block;
        padding: 2px 12px;
        border-radius: 12px;
        background: #4caf50;
        color: #fff;
        font-weight: bold;
        font-size: 13px;
        min-width: 48px;
        text-align: center;
    }

    .deleted-tag {
        display: inline-block;
        padding: 2px 12px;
        border-radius: 12px;
        background: #ccc;
        color: #fff;
        font-weight: bold;
        font-size: 13px;
        min-width: 48px;
        text-align: center;
    }
}
</style>